package XML与JSON.使用DOM4J;
/*
这是我们需要创建的 XML −

<?xml version = "1.0" encoding = "UTF-8"?>
<cars>
   <supercars company = "Ferrari">
      <carname type = "formula one">Ferrari 101</carname>
      <carname type = "sports">Ferrari 202</carname>
   </supercars>
</cars>
*/

import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class DOM4J创建xml {

   public static void main(String[] args) {
      
      try {
         Document document = DocumentHelper.createDocument();
         Element root = document.addElement( "cars" );//根元素
         Element supercarElement = root.addElement("supercars").addAttribute("company", "Ferrai");

         supercarElement.addElement("carname").addAttribute("type", "Ferrari 101").addText("Ferrari 101");

         supercarElement.addElement("carname").addAttribute("type", "sports").addText("Ferrari 202");

         // Pretty print the document to System.out 1.createPrettyPrint()：完美型多行输出  2.createCompactFormat()：紧凑型一行输出
         OutputFormat format = OutputFormat.createPrettyPrint();//.createCompactFormat();
         //XMLWriter writer = new XMLWriter( System.out, format );//输出至控制台
         OutputStream output=new FileOutputStream("src\\main\\java\\XML与JSON\\使用DOM4J\\output.txt");//ClassPath为当前目录
         XMLWriter writer = new XMLWriter( output, format );//输出至文件
         writer.write( document );
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}
/*
<?xml version="1.0" encoding="UTF-8"?>

<cars>
  <supercars company="Ferrai">
    <carname type="Ferrari 101">Ferrari 101</carname>
    <carname type="sports">Ferrari 202</carname>
  </supercars>
</cars>
*/